package com.atguigu.ssyx.product.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.ssyx.product.service.FileUploadService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * ClassName: FileUploadServiceImpl
 * Package: com.atguigu.ssyx.product.service.impl
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-09-26
 * Time: 10:12
 */

@Service
public class FileUploadServiceImpl implements FileUploadService {

    //从配置文件中 取到相关的值
    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.keyid}")
    private String accessKeyId;

    @Value("${aliyun.keysecret}")
    private String accesskeysecret;

    @Value("${aliyun.bucketname}")
    private String bucketName;

    //上传文件
    @Override
    public String uploadFile(MultipartFile file) {
        String filePath = "D:\\localpath\\examplefile.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accesskeysecret);

        try {
            //获取输入流
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            // 参数说明 1 bucket 名称
            // 2 上传文件的路径 + 名称
            // 文件的输入流
            // 3 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            //这里直接是文件名 但是文件名可能重复 发生覆盖
            //使用UUID 去掉-
            String s = UUID.randomUUID().toString().replace("-","");
            //拼接起来
            originalFilename  = s + originalFilename;
            //对文件进行分组 根据日期进行分组 2023/10/10/01.jpg
            //得到当前年月日的时间
            String currentDateTime = new DateTime().toString("yyyy/MM/dd");
            originalFilename = currentDateTime + "/" + originalFilename;
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucketName,originalFilename,inputStream);
            //设置改属性可以返回response 如果不设置 则返回的response为空
            putObjectRequest.setProcess("true");

            // 创建PutObject请求。上传的方法
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println(result.getResponse().getStatusCode());
            System.out.println(result.getResponse().getUri());
            System.out.println(result.getResponse().getErrorResponseAsString());
            String uri = result.getResponse().getUri();
            return uri;
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
